/*
 * LinearInterpolator.cpp
 *
 *  Created on: 23 Aug 2011
 *      Author: Allan
 */

#include "LinearInterpolator.h"


LinearInterpolator::LinearInterpolator() 
{}

LinearInterpolator::LinearInterpolator(const vector<double>& xi, const vector<double>& yi) :
xi(xi), yi(yi)
{}

const double LinearInterpolator::operator()(double x) const
{
	// The number of interpolation points
	const unsigned N = xi.size();
	
	// Check if x is less than the smallest interpolation x-point
	if(x < xi[0]) 
		return yi[0];
	
	// Check if x is larger than the largest interpolation x-point
	if(x > xi[N-1]) 
		return yi[N-1];
	
	// Otherwise, find the interval where x lives
	const int k = FindPosition(x);
	
	return (yi[k+1] - yi[k])/(xi[k+1] - xi[k]) * (x - xi[k]) + yi[k];
}

const unsigned LinearInterpolator::FindPosition(double x) const
{
	// The number of interpolation points
	const unsigned N = xi.size();
	
	for(unsigned k = 0; k < N-1; ++k)
		if(xi[k] <= x && x <= xi[k+1])
			return k;
	
	return -1;
}
